import router from '@/router'
import { useUserStore } from '@/stores'
import axios, { AxiosError, type Method } from 'axios'
import { showToast } from 'vant'

// 创建 axios 实例
const instance = axios.create({
  // 1. 基础地址，超时时间
  baseURL: 'https://consult-api.itheima.net', // 接口基础地址
  timeout: 10000, // 请求超时时间（10秒）
})

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 2. 携带token
    const store = useUserStore()
    if (store.user?.token && config.headers) {
      config.headers.Authorization = `Bearer ${store.user.token}`
    }
    return config
  },
  (err) => Promise.reject(err),
)

// 响应拦截器
instance.interceptors.response.use(
  (res) => {
    // 3. 处理业务失败
    if (res.data.code !== 10000) {
      showToast(res.data.message || '业务失败')
      return Promise.reject(res.data)
    }
    // 4. 摘取核心响应数据
    return res.data
  },
  (err: AxiosError) => {
    // 5. 处理401错误
    if (err.response?.status === 401) {
      const store = useUserStore()
      // 删除用户信息
      store.delUser()
      // 跳转到登录
      router.push({
        path: '/login',
        query: {
          returnUrl: router.currentRoute.value.fullPath,
        },
      })
    }
    return Promise.reject(err)
  },
)

export default instance

type Data<T> = {
        code: number
        message: string
        data: T
      }

export const request = <T>(url: string, method: Method, submitData?: object) => {
  if (method.toUpperCase() === 'GET') {
    return instance.request<unknown, Data<T>>({
      url,
      method,
      params: submitData,
    })
  } else {
    return instance.request<unknown, Data<T>>({
      url,
      method,
      data: submitData,
    })
  }
}
